package concurrent.reentrantlock;

/**
 * 简单实现一个可重入锁
 */
public class MyReentrantLock {
    boolean isLocked = false;
    Thread lockedBy = null;

    /**
     * 可重入需要计数
     */
    int lockedCount = 0;

    public synchronized void lock() throws InterruptedException{
        Thread thread = Thread.currentThread();
        while(isLocked && lockedBy != thread) {
            wait();
        }
        isLocked = true;
        lockedCount++;
        lockedBy = thread;
    }
    public synchronized void unlock(){
        if(Thread.currentThread() == this.lockedBy) {
            lockedCount--;
            if (lockedCount == 0) {
                isLocked = false;
                notify();
            }
        }
    }
}
